package com.itheima.customerTest;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Customer01_shortMessage {
    private final static String EXCHANGE_FANOUT = "publishSubscribe";
    private final static String QUEUE_MESSAGE = "shortMessage";
    private final static String QUEUE_INFOR = "information";


    public static void main(String[] args) {
//        通过工厂获取连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
//        设置工厂属性
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
//        创建与rabbit服务器的连接
        try {
            connection = connectionFactory.newConnection();
//            创建与交换机的连接通道，每个连接可以创建多个通道，每个通到代表一个会话任务
            Channel channel = connection.createChannel();

//            声明交换机
            channel.exchangeDeclare(EXCHANGE_FANOUT, BuiltinExchangeType.FANOUT);
//            声明队列
//            String queue, boolean durable, boolean exclusive, boolean autoDelete,Map<String, Object> arguments
//           对列参数：队列名称，是否持久化，是否独占，是否不用时自动删除，队列参数设置
            channel.queueDeclare(QUEUE_MESSAGE, true, false, false, null);

//           监听rabbit服务器的消息体
            DefaultConsumer defaultConsumer=new DefaultConsumer(channel){


                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    long tag = envelope.getDeliveryTag();
                    String envelopeExchange = envelope.getExchange();
                    String routingKey = envelope.getRoutingKey();
                    String msg=new String(body,"utf-8");
                    System.out.println(msg);
                }
            };
         channel.basicConsume(QUEUE_MESSAGE,true,defaultConsumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {

        }
    }
}
